<template>
  <div class="echartsContainer">
    <div ref="deviceEchartRef" class="showEchart"></div>
  </div>
</template>
<script lang="ts" setup>
import _ from "lodash";
import { reactive, ref, onMounted, inject } from "vue";
import { useRoute } from "vue-router";
import { AnalysisReset } from "@/utils/common"; // 导入表格api方法生成器
import * as echarts from "echarts/core";
import {
  TitleComponent,
  TitleComponentOption,
  ToolboxComponent,
  ToolboxComponentOption,
  TooltipComponent,
  TooltipComponentOption,
  GridComponent,
  GridComponentOption,
  LegendComponent,
  LegendComponentOption,
  BrushComponent,
  BrushComponentOption,
  MarkAreaComponent,
  MarkAreaComponentOption,
  VisualMapComponent,
  VisualMapComponentOption,
  CalendarComponent,
  CalendarComponentOption,
  DataZoomComponent,
  DataZoomComponentOption,
} from "echarts/components";
import {
  LineChart,
  LineSeriesOption,
  ScatterChart,
  ScatterSeriesOption,
  HeatmapChart,
  HeatmapSeriesOption,
} from "echarts/charts";
import { UniversalTransition } from "echarts/features";
import { CanvasRenderer } from "echarts/renderers";
echarts.use([
  TitleComponent,
  ToolboxComponent,
  TooltipComponent,
  GridComponent,
  LegendComponent,
  LineChart,
  CanvasRenderer,
  UniversalTransition,
  ScatterChart,
  CanvasRenderer,
  UniversalTransition,
  BrushComponent,
  MarkAreaComponent,
  VisualMapComponent,
  HeatmapChart,
  CalendarComponent,
  DataZoomComponent,
]);
type EChartsOption = echarts.ComposeOption<
  | TitleComponentOption
  | ToolboxComponentOption
  | TooltipComponentOption
  | GridComponentOption
  | LegendComponentOption
  | LineSeriesOption
  | BrushComponentOption
  | MarkAreaComponentOption
  | ScatterSeriesOption
  | VisualMapComponentOption
  | HeatmapSeriesOption
  | CalendarComponentOption
  | DataZoomComponentOption
>;

const config = inject("config") as any;
const analysis = inject("analysis") as any;

// 初始化重组分析数据类
const resetAnalysis = new AnalysisReset();

const state: {
  charts: any[];
} = reactive({
  charts: [],
});
const Fileds: {
  optionsSeries: any[]; //折线图实际数据
  optionsLegendData: any[]; //折线图legen标识
  customOptions: any; //自定义折线图配置
  optionNull: any; //折线图非数据占位
  optionNullTwo: any; //折线图无数据占位
} = reactive({
  optionsSeries: [],
  optionsLegendData: [],
  customOptions: {
    backgroundColor: "transparent",
    tooltip: {
      trigger: "axis",
    },
    legend: {
      data: [],
      textStyle: {},
      top: "3%",
    },
    grid: {
      left: "3%",
      right: "4%",
      bottom: "3%",
      containLabel: true,
    },
    toolbox: {
      feature: {
        dataZoom: {
          yAxisIndex: "none",
        },
        restore: {},
        saveAsImage: {},
      },
    },
    xAxis: {
      type: "category",
      boundaryGap: false,
      // data: periodOfTime(state.rightHour - 0, state.rightMinute - 0),
      data: [],
      // axisLabel: {
      //   interval: 5, // 设置数据间隔
      //   // rotate: -38, // 标题倾斜
      // },
    },
    yAxis: {
      type: "value",
      boundaryGap: [0, "100%"],
      name: "",
      axisLabel: {
        interval: 5, // 设置数据间隔
        // rotate: -38, // 标题倾斜
      },
      // max: 20, // 这里将Y轴的最大值设为100
    },
    dataZoom: [
      {
        type: "slider", // 内置型数据区域缩放组件
        xAxisIndex: 0, // 设置对哪个 x 轴进行缩放
        start: 0, // 数据窗口范围的起始百分比
        end: 100, // 数据窗口范围的结束百分比
      },
      {
        type: "slider", // 滑动条型数据区域缩放组件
        yAxisIndex: 0, // 设置对哪个 x 轴进行缩放
        start: 0, // 数据窗口范围的起始百分比
        end: 100, // 数据窗口范围的结束百分比
        // bottom: 10, // 滑动条组件距离底部的距离
      },
    ],
    series: [],
  },
  optionNull: {
    backgroundColor: "transparent",
    title: {
      text: "无法使用图表展示，请切换为数据",
      x: "center",
      y: "center",
      textStyle: {
        fontWeight: "normal",
        fontSize: 16,
      },
    },
  },
  optionNullTwo: {
    backgroundColor: "transparent",
    title: {
      text: "暂无数据",
      x: "center",
      y: "center",
      textStyle: {
        fontWeight: "normal",
        fontSize: 16,
      },
    },
  },
});

const deviceEchartRef = ref<HTMLDivElement>(); //获取图表展示的dom 基础数据折现图

//生成自定义图表数据
const getDiffFiledsData = (fileds: any[]) => {
  let originObj: any = {
    name: "电表",
    type: "line",
    stack: "Total",
    data: [],
    markPoint: {
      data: [
        { type: "max", name: "Max" },
        { type: "min", name: "Min" },
      ],
    },
  };
};

//生成自定义折线图
const initCustom = () => {
  const paramsChart = config.layout.isDark
    ? echarts.init(deviceEchartRef.value as HTMLDivElement, "dark")
    : echarts.init(deviceEchartRef.value as HTMLDivElement);
  let options = Fileds.customOptions;
  console.log("生成自定义折线图", options);

  paramsChart.setOption(options);
  state.charts.push(paramsChart);
};

//遍历数据便于图表展示
const resetForEcharts = (data: any[]) => {
  let len = data.length;
  let option: any = [];
  let optionName: any = [];
  let optionxAxisData: any = [];
  let temObj: any = {
    name: "槽体内液体温度T1",
    type: "line",
    stack: "Total",
    data: [],
    markPoint: {
      data: [
        { type: "max", name: "Max" },
        { type: "min", name: "Min" },
      ],
    },
  };
  for (const key in data[0]) {
    ["时", "日", "月"].some((el: any) => {
      key.includes(el);
      if (key.includes(el)) {
        optionxAxisData.push(key);
      }
    });
  }
  for (let i = 0; i < len; i++) {
    let temp = _.cloneDeep(temObj);
    //机柜名称-用能标签
    temp.name =
      data[i].cabinetName + "-" + analysis.tags["summary"][data[i].summary];
    //关于Echarts多条折线图堆叠折线绘制错误问题
    temp.stack = "Total" + i;
    for (const key in data[i]) {
      ["时", "日", "月"].some((el: any) => {
        key.includes(el);
        if (key.includes(el)) {
          temp.data.push(data[i][key]);
        }
      });
    }
    optionName.push(temp.name);
    option.push(temp);
  }
  Fileds.customOptions.series = option; //主要数据
  Fileds.customOptions.legend.data = optionName; //legend标识数据
  Fileds.customOptions.xAxis.data = optionxAxisData; //x轴
  console.log("遍历数据便于图表展示", option, Fileds.customOptions);
  initCustom(); //初始化自定义图表
};

//无数据使用占位图表
const initNullTwo = () => {
  const paramsChart = config.layout.isDark
    ? echarts.init(deviceEchartRef.value as HTMLDivElement, "dark")
    : echarts.init(deviceEchartRef.value as HTMLDivElement);
  let options = Fileds.optionNullTwo;
  console.log("无数据使用占位图表", options);
  paramsChart.setOption(options);
  state.charts.push(paramsChart);
};

//获取重组数据
const getAnalysis = () => {
  let filter: any = {
    date: analysis.date,
    siteids: analysis.siteids + "", //序列化
    start: analysis.start,
    end: analysis.end,
    siteid: analysis.siteid,
  };
  //因为年月日报调用不同接口 需要判断传参是年月日
  let filterLen = filter.date.split("-").length;
  analysis.getList(filter).then((result: any) => {
    resetAnalysis.resetGateway(result.rows).then(async (res: any) => {
      const promises = resetAnalysis.getCabinetName(res, analysis);
      Promise.all(promises).then(() => {
        if (result.rows.length == 0) {
          //无数据占位
          initNullTwo();
          return;
        }
        // 重组分析分项数据
        resetAnalysis.resetFields(result.rows).then((res: any) => {
          resetAnalysis
            .resetTag(res, analysis, filterLen)
            .then((res: any) => {
              console.log("重组分析分项数据echarts", res);
              let len = res.length;
              for (let i = 0; i < len; i++) {
                res[i].cabinetName = analysis.cabinetNameArrForTable.get(
                  res[i].gcode
                );
              }
              resetForEcharts(res);
            })
            .catch((err: any) => {});
        });
      });
    });
  });
};

onMounted(() => {
  getAnalysis(); //获取重组数据
});
</script>
<style lang="scss" scoped>
.echartsContainer {
  width: 100%;
  height: 65vh;
  margin: 0 auto;
  .showEchart {
    margin: 0 auto;
    width: 95%;
    height: 95%;
  }
}
</style>
